package com.irdstudio.apicenter.gateway.util;

import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.irdstudio.apicenter.gateway.comm.MaccsPacket;
import com.irdstudio.apicenter.gateway.comm.tcp.MaccsSocketClient;

/**
 * Servlet辅助类
 * @author guangming.li
 * @version 1.0
 * @date 2015-05-21
 */
public class ServletUtil {
	
	/**
	 * 遍历HTTP请求中的参数，将其放放入到map中
	 * @return
	 */
	private final static Logger logger = LoggerFactory
			.getLogger(MaccsSocketClient.class);
	public static MaccsPacket getAllRequestValues(
			HttpServletRequest request) {
		MaccsPacket uvo = new MaccsPacket();
		//added by Tangxun on 2015/9/25
		try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		Enumeration<String> e = request.getParameterNames();
		while (e.hasMoreElements()) {
			String name = e.nextElement();
			String value1 = request.getParameter(name);
			byte[] bs = value1.getBytes();
			
			String value = value1;
			uvo.addVariable(name, value);			
		}
		// vmap.put("sourceip", getClientIP(request));
		// //将手机客户端用户IP添加到数据集合中.
		// // vmap.put("clientIp",getClientIP(request));
		// log.debug("Request Parameter ["+vmap.toString() + "]");
		//		
		// StringBuffer sb=new StringBuffer();
		// sb.append("Cookie:").append(request.getHeader("Cookie") );
		// log.debug("header:"+sb.toString());

		return uvo;
	}
	
	protected void setCookie(String setCookie,int httpServiceIndex) {
//		String setCookie=list.get(1).toString();
//		String lb_cookie= "LB_SLOT=" + httpServiceIndex ;
//		log.debug("....Set-Cookie:"+setCookie);
		if(setCookie.indexOf(";")!=-1){
			String ck[]=setCookie.split(";");
			String cookie=ck[0];
			String cookiePath=ck[1];
			String cookiePath_=cookiePath.substring(0,cookiePath.indexOf("=")+1)+"/";
			//setCookie=cookie+";"+lb_cookie+";"+cookiePath_;
			setCookie=cookie+";"+cookiePath_;
		}
//		log.debug("....Set-Cookie:" + setCookie);
//		response.setHeader("Set-Cookie", setCookie);
//		Cookie c = new Cookie("LB_SLOT", httpServiceIndex + "");
//		response.addCookie(c);
	}	
	/**
	 * 取客户端的真实IP地址 
	 * @param request
	 * @return
	 */
	public static String getRealClientIP(HttpServletRequest request) {
		// 从SSL取客户IP
		String ip = request.getHeader("Proxy-Client-IP");// 客户IP
		/*
		 * //从格尔的SSL取 if(ip == null || ip.length() == 0 ||
		 * "unknown".equalsIgnoreCase(ip)) { // 获取客户IP Cookie[] cookies =
		 * request.getCookies(); if(cookies == null) { cookies = new Cookie[0];
		 * } for(int i = 0; i < cookies.length; i ++) { Cookie cookie =
		 * cookies[i]; if("KOAL_CLIENT_IP".equals(cookie.getName())) { ip =
		 * cookie.getValue(); } } }
		 */
		// 反向代理
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("x-forwarded-for");
		}
		/*
		 * if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
		 * { ip = request.getHeader("$WSRA"); } if(ip == null || ip.length() ==
		 * 0 || "unknown".equalsIgnoreCase(ip)) { ip =
		 * request.getHeader("WL-Proxy-Client-IP"); }
		 */
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
			if (ip.equals("127.0.0.1") || ip.equals("0:0:0:0:0:0:0:1")) {
				// 根据网卡取本机配置的 IP
				InetAddress inet = null;
				try {
					inet = InetAddress.getLocalHost();
				} catch (UnknownHostException e) {
					// e.printStackTrace();
				}
				ip = inet.getHostAddress();
			}
		}

		// 存在多级反向代理的情况下，从x-forwarded-for获取的值为逗号分隔的ip串
		if (ip.indexOf(",") > 0) {
			ip = ip.substring(0, ip.indexOf(",")).trim();
		}

		return ip;
	}
}
